#include <bits/stdc++.h>
// 2025/01/18
// tag: simulation
// Author: Zhang Muen
using namespace std;

int m, n, order[401], t[21][21], num[21][21], t2[21], todo[21];
bool machine[21][8001];

signed main()
{
    cin >> m >> n;
    for (int i = 1; i <= n * m; i++)
        cin >> order[i];
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> num[i][j];
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> t[i][j];
    int ans = 0;
    for (int i = 1; i <= n * m; i++){
        int x = order[i], y = ++todo[order[i]], j = max(t2[x], 1);
        for (int cnt = 0; cnt != t[x][y]; j++){
            if (machine[num[x][y]][j] == false)
                cnt++;
            else
                cnt = 0;
        }
        ans = max(ans, j);
        for (int k = j - 1; k >= j - t[x][y]; k--)
            machine[num[x][y]][k] = true;
        t2[x] = j;
    }
    cout << ans - 1;
    return 0;
}